#include "Common.hpp"

class udp_server
{
public:
    udp_server(uint16_t port = 8080)
        :_port(port)
    {

    }
    void Init(){
        _fd = socket(AF_INET,SOCK_DGRAM,0);
        if (_fd < 0){
            LOG(ERROR) << "socket create error";
            exit(-1);
        }
        uint16_t port = ::htons(_port);
        //bind操作
        sockaddr_in local;
        local.sin_family = AF_INET;
        local.sin_port = port; //把本地字节序列转化为网络字节序列
        local.sin_addr.s_addr = INADDR_ANY; //指的是这个服务器接受来则任何ip的ip访问
        socklen_t len = sizeof(local);
        if(::bind(_fd,CONV(&local),len) < 0){
            LOG(ERROR) << "bind error";
            exit(-1);
        }
    }
    void Start(){
          char buffer[1024];
        sockaddr_in peer;
        socklen_t Len = sizeof(peer);
        while(true){
            ssize_t n = ::recvfrom(_fd,buffer,1024,0,CONV(&peer),&Len);
            if (n > 0){
                string client = "echo server say# ";
                buffer[n] = 0;
                client += buffer;
                char Ip[64];
                ::inet_ntop(AF_INET,&(peer.sin_addr),Ip,64);
                std::string ip = Ip;
                string port = to_string(::ntohs(peer.sin_port));
                LOG(INFO) << ip << ":" << port << "say#" << buffer;
                sendto(_fd,client.c_str(),client.size(),0,CONV(&peer),Len);
            }
        }
    }
    ~udp_server(){
        ::close(_fd);
    }
private:
    int _fd;
    uint16_t _port;
};
